<template>
    <el-container class="team-file-container">
        <el-header class="team-file-container-header" v-loading="loading">
            <div class="rongliang">
                容量：{{ useflow.usesize }} / {{ useflow.size }}
            </div>
            <div class="col-progress">
                <el-progress :percentage="useflow.percentagesize" />
            </div>
            <div class="rongliang">
                月流量：{{ useflow.useflow }} / {{ useflow.flow }}
            </div>
            <div class="col-progress">
                <el-progress :percentage="useflow.percentageflow" />
            </div>
        </el-header>
        <div class="team-file-btn-box margin-top20" size="default" :inline="true">
            <el-button class="margin-right20" type="primary" size="default" @click="start">刷新</el-button>
            <el-upload :disabled="!!percentage" action="https://jsonplaceholder.typicode.com/posts/" :auto-upload="true"
                :http-request="request" :show-file-list="false">
                <el-button :disabled="!!percentage" ref="buttonRef" size="default" type="primary">
                    <el-icon :size="20">
                        <Upload />
                    </el-icon>
                    &nbsp;
                    {{ percentage ? '上传中...' + percentage + '%' : '上传文件' }}
                </el-button>
            </el-upload>
        </div>
        <el-main class="team-file-content padding0 margin-top20">
            <el-table v-loading="loading" :data="tableData" height="76vh">
                <template v-slot:empty>
                    <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
                </template>
                <el-table-column prop="name" label="文件名" width=""></el-table-column>
                <el-table-column prop="type" label="文件类型" width=""></el-table-column>
                <el-table-column prop="createdAt" label="上传时间" width="">
                    <template #default="{ row }">
                        {{ TimeYH(row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column prop="size" label="文件大小">
                    <template #default="{ row }">
                        {{ renderSize(Number(row.size)) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-tooltip effect="dark" content="下载链接有效期：5分钟" placement="left">
                            <el-button :icon="Download" type="primary" size="default" @click="download(row)">
                                下载
                            </el-button>
                        </el-tooltip>
                        <el-button type="primary" size="default" v-show="isAdmin" @click="del(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pager" :page-size="limit" :total="count" @current-change="change"
                layout="total,prev, pager, next" :current-page="Math.floor(offset / limit) + 1"></el-pagination>
        </el-main>

    </el-container>
</template>

<script setup lang="ts">
import { Download, Upload } from '@element-plus/icons-vue';
import OSS from 'ali-oss';
import { ElButton, ElMessage, ElMessageBox, ElNotification, ElUpload, UploadRequestOptions, } from 'element-plus';
import { debounce } from 'underscore';
import { v4 } from 'uuid';
import { computed, h, onMounted, ref, watch } from 'vue';
import { useStore } from "vuex";
import { asynccreateteamfile, asyncdelectteamfile, asyncgetteamfile, asyncgetteamflow, asyncupdateteamflow, asyncuploadAccess, ossupload } from '../../../api';
import { Storekey } from '../../../interface';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { TimeYH } from '../../../util/time';
import { updateoss2 } from '../../../util/updateoss';

const store = useStore(Storekey)
const user = computed<Studycodemodel.Iuser>(() => {
    return store.getters.getuser;
});
const teamId = computed(() => {
    return Number(user.value?.teamid)
})
const isAdmin = computed(() => {
    return user.value?.isAdmin
})

const teamFlow = ref<Studycodemodel.Iteamflow>()
async function setflow() {
    try {
        teamFlow.value = await asyncgetteamflow({ teamid: teamId?.value })
    } catch (e) {
        teamFlow.value = undefined
        console.error(e)
    }
}
const bucketobj = ref()


const tableData = ref<Studycodemodel.Iteamfile[]>([])
const percentage = ref(0)
const count = ref(0)
const offset = ref(0);
const limit = ref(20);
const loading = ref(false)
const name = ref('')

function debounce1() {
    return debounce(() => {
        let _like: [keyof Studycodemodel.Iteamfile, any] | undefined;
        if (name.value) {
            _like = ["name", name.value];
        }
        loading.value = true
        asyncgetteamfile({
            _offset: offset.value,
            _limit: limit.value,
            _like,
            teamid: teamId.value,
        }).then(e => {
            loading.value = false
            tableData.value = e.rows
            count.value = e.count
        })
        setflow()
    }, 300);
}
const start = debounce1();

watch([offset, limit, name], (e, r) => {
    start();
});

const o = ref<OSS>()

onMounted(async () => {
    const res = await ossupload()
    o.value = new OSS({
        region: "oss-cn-qingdao",
        accessKeyId: res.accessKeyId,
        accessKeySecret: res.accessKeySecret,
        stsToken: res.securityToken,
        bucket: 'ojteam',
        refreshSTSToken: async () => {
            const info = await ossupload();
            return {
                accessKeyId: info.accessKeyId,
                accessKeySecret: info.accessKeySecret,
                stsToken: info.securityToken
            }
        }

    })
    start()
})

function change(r: number) {
    offset.value = (r - 1) * 10;
}


const open1 = () => {
    ElNotification({
        title: '上传中',
        message: h('i', { style: 'color: teal' }, 'This is a reminder'),
    })
}

async function del(V: Studycodemodel.Iteamfile) {
    if (!isAdmin.value) {
        ElMessage.error('没有权限')
    }
    ElMessageBox.confirm("确定要删除?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "",
        type: "warning",
    })
        .then(async () => {
            try {
                await asyncdelectteamfile(V)
                if (V.url) {
                    await o.value?.delete(V.url)
                }
                start()
            } catch (e) {
                ElMessage({
                    message: String(e),
                    type: "error",
                });
            }
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "已取消",
            });
        });

}

const useflow = computed(() => {
    const { usesize = 0, size = 1021 * 1024 * 1024 * 5, flow = 1021 * 1024 * 1024 * 10, useflow = 0 } = teamFlow.value || {}
    return {
        size: renderSize(size),
        usesize: renderSize(usesize),
        flow: renderSize(flow),
        useflow: renderSize(useflow),
        percentageflow: Math.floor(useflow / flow * 100),
        percentagesize: Math.floor(usesize / size * 100),
        _usesize: usesize,
        _size: size,
        _flow: flow,
        _useflow: useflow,
    }
})

async function download(name: Studycodemodel.Iteamfile) {
    if (useflow.value._useflow > useflow.value._flow) {
        ElMessage.error('本月团队资料流量已用完，如需帮助请联系助教老师或管理员')
        return
    }
    const data = o.value?.signatureUrl(String(name.url), {
        expires: 300
    })
    await asyncupdateteamflow({ ID: teamFlow.value?.ID, useflow: teamFlow.value?.useflow, size: name.size, teamid: teamId.value, name: name.name, teamfileid: name.ID })
    window.open(data, '_blank')
    setflow()
}

const upload = ref<typeof ElUpload>();
async function request(option: UploadRequestOptions) {
    if (upload.value) upload.value.clearFiles();
    if (option.file.size > 1024 * 1024 * 1024) {
        ElMessage.warning('提示：文件资料大小为1G以内，如需上传更大文件请联系助教老师')
        return
    }

    if (useflow.value._usesize > useflow.value._size) {
        ElMessage.error('团队存储空间已满，如需帮助请联系助教老师或管理员')
        return
    }
    if (option.file.name.length > 128) {
        ElMessage.error('文件名称最大长度128')
        return
    }
    try {
        const res = await asyncuploadAccess({ teamid: teamId.value })
        const v = v4()
        const d = await updateoss2([option.file], { bucket: 'ojteam', url: `${teamId.value}/${v}/${option.file.name}`, res }, () => { }, {
            progress
        });
        percentage.value = 0
        const sp = option.file.name.split('.')
        await asynccreateteamfile({
            name: option.file.name,
            url: d.name,
            size: option.file.size,
            type: sp.length === 1 ? '' : sp.pop(),
            teamid: teamId.value
        })
        start()
    } catch (e: any) {
        console.log(e)
        ElMessage.error(e)
    }
}

function progress(per: number, checkpoint: any, res: any) {
    percentage.value = Math.floor(per * 100)
}

function renderSize(value: number) {
    if (!value) {
        return "0 Bytes";
    }
    var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
    var index = 0;
    var srcsize = parseFloat(String(value));
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    var size = srcsize / Math.pow(1024, index);
    return size.toFixed(2) + unitArr[index];
}
</script>

<style scoped>
.team-file-container {
    border-radius: 4px;
    overflow-x: hidden;
    /* margin-bottom: 24px; */
    /* border: 1px solid rgba(117, 117, 117, 0.4);
    box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1), 0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
    background-color: #fff; */
}

.team-file-container-header {
    padding: 0;
    height: auto;
    font-size: 16px;
    font-weight: 700;
    display: flex;
    align-items: center;
}

.team-file-btn-box {
    display: flex;
}

.team-file-content {}

.rongliang {
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
    font-size: 14px;
    text-align: right;
    padding: 0;
    display: inline-block;
    margin-right: 20px;
}

.col-progress {
    align-items: center;
    width: 200px;
}
</style>
